package cn.mayaslight.common.utils;

import cn.mayaslight.common.handler.IHandler;

public class SyncUtils {

	private static final String LOCK_PREFIX = "LOCK_PREFIX_____";

	public static Object getLock(String key) {
		StringBuilder sb = new StringBuilder();
		sb.append(LOCK_PREFIX).append(key);
		return sb.toString().intern();
	}

	public static <T> T sync(T obj, Class<T> clazz, Object syncLock, Object... params) {
		if (obj == null) {
			synchronized (syncLock) {
				if (obj == null) {
					obj = ReflectUtils.newInstance(clazz, params);
				}
			}
		}
		return obj;
	}

	public static <T> T sync(T obj, Class<T> clazz, Object syncLock, IHandler<T, T> preHandler, IHandler<T, T> afterHandler, Object... params) {
		if (obj == null) {
			synchronized (syncLock) {
				if(preHandler != null){
					obj = preHandler.handle(obj);
				}
				if (obj == null) {
					obj = ReflectUtils.newInstance(clazz, params);
					if(afterHandler != null){
						obj = afterHandler.handle(obj);
					}
				}
			}
		}
		return obj;
	}

}
